﻿using System;
using System.Collections.Generic;
using System.IO;
//using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Text;
using Telerik.Sitefinity.Services.Migration;
using MigrationExportService;
using System.Web.Hosting;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetMasterPagesList()
		{
			List<MigrationItemContentDefinition> output = new List<MigrationItemContentDefinition>();

			string[] masterPages = { };
			string appMasterPath = HostingEnvironment.MapPath("~/App_Master");
			try
			{
				masterPages = Directory.GetFiles(appMasterPath, "*.master");
			}
			catch (IOException) { }
			catch (UnauthorizedAccessException) { };

			foreach (var masterPage in masterPages)
			{
				var micd = new MigrationItemContentDefinition();
				micd.Name = Path.GetFileName(masterPage);
				output.Add(micd);
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetMasterPagesListResponse", output);
		}

		public Message GetSingleMasterPage(Message masterPageDefinitionParam)
		{
			MigrationItemContentDefinition param = masterPageDefinitionParam.GetBody<MigrationItemContentDefinition>();
			string masterPageContents = MigrationUtils.GetSafeTextFileContents(HostingEnvironment.MapPath(String.Format("~/App_Master/{0}", param.Name)));

			MigrationMasterPage result = new MigrationMasterPage();
			result.MasterPageName = param.Name;
			result.MasterPagePath = String.Format("~/App_Master/{0}", param.Name);
			result.MasterPageContents = masterPageContents;
			result.IsPrimary = true;

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetSingleMasterPageResponse", result);
		}
	}
}
